﻿
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.Workshops.Dtos;
using KDS.Mes.Authorization;
using KDS.Mes.Dto;
using KDS.Mes.Mes.Factorys;

namespace KDS.Mes.Mes.Workshops
{
    /// <summary>
    /// 车间信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Basic_Workshops)]
    public class WorkshopAppService : MesAppServiceBase, IWorkshopAppService
    {
        private readonly IRepository<Workshop, int> _workshopRepository;
        private readonly IWorkshopListExcelExporter _workshopListExcelExporter;
        private readonly IRepository<Factory, int> _factoryRepository;


        private readonly WorkshopManage _workshopManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public WorkshopAppService(
            IRepository<Workshop, int> workshopRepository,
            WorkshopManage workshopManage, 
            IWorkshopListExcelExporter workshopListExcelExporter,
            IRepository<Factory, int> factoryRepository

        )
        {
            _workshopRepository = workshopRepository;
            _workshopManage = workshopManage;
            _workshopListExcelExporter = workshopListExcelExporter;
            _factoryRepository = factoryRepository;
        }

        #region 车间信息管理

        /// <summary>
        /// 根据查询条件获取车间信息分页列表
        /// </summary>
        public async Task<PagedResultDto<WorkshopListDto>> GetPagedWorkshopsAsync(GetWorkshopInput input)
        {

            var query = _workshopRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var workshopCount = await query.CountAsync();

            var workshops = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var workshopListDtos = workshops.MapTo<List<WorkshopListDto>>();
            return new PagedResultDto<WorkshopListDto>(
            workshopCount,
            workshopListDtos
            );
        }

        /// <summary>
        /// 根据FactoryId获取对应的Workshop
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<ComboboxItemDto> GetWorkshopByFactoryId(NullableIdDto<int> input)
        {
            List<ComboboxItemDto> output = new List<ComboboxItemDto>();
            var query = _workshopRepository.GetAll()
                .Where(u => u.FactoryId == input.Id).ToList();
            //query = query
            output = query
               .Select(c => new ComboboxItemDto(c.Id.ToString(), c.WorkshopName))
               .ToList();
            return output;
        }


        public PagedResultDto<WorkshopListDto> GetPagedWorkshops(GetWorkshopInput input)
        {
            //初步过滤
            var query = _workshopRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();

            return new PagedResultDto<WorkshopListDto>(tasksCount, taskList.MapTo<List<WorkshopListDto>>());
        }

        /// <summary>
        /// 通过Id获取车间信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetWorkshopForEditOutput> GetWorkshopForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetWorkshopForEditOutput();

            WorkshopEditDto workshopEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _workshopRepository.GetAsync(input.Id.Value);
                workshopEditDto = entity.MapTo<WorkshopEditDto>();
            }
            else
            {
                workshopEditDto = new WorkshopEditDto();
            }

            output.Workshop = workshopEditDto;
            output.Factorys = _factoryRepository.GetAllList()
               .Select(c => new ComboboxItemDto(c.Id.ToString(), c.FactoryName) { IsSelected = output.Workshop.FactoryId == c.Id })
               .ToList();
            return output;
        }


        /// <summary>
        /// 通过指定id获取车间信息ListDto信息
        /// </summary>
        public async Task<WorkshopListDto> GetWorkshopByIdAsync(EntityDto<int> input)
        {
            var entity = await _workshopRepository.GetAsync(input.Id);

            return entity.MapTo<WorkshopListDto>();
        }







        /// <summary>
        /// 新增或更改车间信息
        /// </summary>
        public async Task CreateOrUpdateWorkshopAsync(CreateOrUpdateWorkshopInput input)
        {
            if (input.WorkshopEditDto.Id.HasValue)
            {
                await UpdateWorkshopAsync(input.WorkshopEditDto);
            }
            else
            {
                await CreateWorkshopAsync(input.WorkshopEditDto);
            }
        }

        /// <summary>
        /// 新增车间信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Workshops_Create)]
        public virtual async Task<WorkshopEditDto> CreateWorkshopAsync(WorkshopEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<Workshop>();

            entity = await _workshopRepository.InsertAsync(entity);
            return entity.MapTo<WorkshopEditDto>();
        }

        /// <summary>
        /// 编辑车间信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Workshops_Edit)]
        public virtual async Task UpdateWorkshopAsync(WorkshopEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _workshopRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _workshopRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除车间信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Administration_Roles_Delete)]
        public async Task DeleteWorkshopAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _workshopRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除车间信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Administration_Roles_Delete)]
        public async Task BatchDeleteWorkshopAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _workshopRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion


        #region 车间信息的Excel导出功能


        public async Task<FileDto> GetWorkshopToExcel()
        {
            var entities = await _workshopRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<WorkshopListDto>>();

            var fileDto = _workshopListExcelExporter.ExportWorkshopToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
